package models.campus;

import models.UUIDModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import play.db.jpa.JPA;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 楼层
 */
@Entity
@Table(name = "bd_floors")
public class Floor extends UUIDModel {

    /**
     * 所属小区
     */
    @JoinColumn(name = "campus_building_id")
    @ManyToOne
    public Building building;

    /**
     * 楼层名称
     */
    @Column(name = "name", length = 10)
    public String name;

    public Floor(){}

    public Floor(Building building , String name , AdminUser loginUser){
        this.building = building ;
        this.name = name ;
        this.createdAt = new Date();
        this.createUser = loginUser ;
        this.deleted = DeletedStatus.UN_DELETED ;
        this.belongCompany = loginUser.organization != null ? loginUser.organization : null ;
    }

    /**
     * 按照楼幢查询楼层
     * @param buildingId
     * @return
     */
    public static List<Floor> loadByBuilding(String buildingId){
        return Floor.find(" building.id = ? and deleted = ? order by createdAt " , buildingId , DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public static Floor findByFloorId(String id){
        return Floor.find("id = ? and deleted = ? ", id , DeletedStatus.UN_DELETED).first();
    }

    /**
     *检查是否被使用
     * @param ids
     * @return
     */
    public static String checkIsUsed(String[] ids){
        String idsStr = "'" + UStringUtil.concatStr("','",ids)+"'" ;
        String floorStr = "";
        String sqlSelect = " select b.`name` from bd_rooms a left join bd_floors b on a.campus_floor_id = b.id where a.deleted = 0 and b.id in ("+idsStr+") group by b.`name` " ;
        Query query = Room.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resultList = query.getResultList();
        for(Map<String , Object> map : resultList){
            floorStr += map.get("name") + "," ;
        }

        return floorStr ;
    }

    /**
     *删除
     * @param ids
     */
    public static void deleteFloors(String[] ids){
        String idsStr = "'" + UStringUtil.concatStr("','",ids) + "'" ;
        String sqlUpdate =  " update bd_floors a set a.deleted = 1 where a.id in ("+idsStr+")";
        JPA.em().createNativeQuery(sqlUpdate).executeUpdate() ;
    }

    /**
     * 通过楼宇和楼层名称查询
     * @param building
     * @param name
     * @return
     */
    public static Floor findBybuildingAndName(Building building ,String name){
        return Floor.find("deleted = ? and building = ? and name = ? ",DeletedStatus.UN_DELETED ,building , name).first();
    }
}
